﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Sumen.Library.Classes.Common;
using Sumen.Library.Enum;
using Sumen.Business.Data;
using Sumen.Model.Model;

namespace Sumen.Business.Presenter.Inventory
{
    public class InwardPresenter
    {

        public int Add(List<inventory_details> pObjectValue, stock_inward pInward)
        {
            Dao dao = new Dao(true, true);
            //add inward
            decimal vat = (decimal)(1f + (float)pInward.Inw_VAT / 100f);
            //pInward.Inw_Amount *= vat;
            dao.Add(pInward);

            //check ship greater-->update
            int sumQuantity = (int)pObjectValue.Sum(s => s.Invd_Quantity);
            decimal newShip = (decimal)(pInward.Inw_Ship_Price / sumQuantity);

            bool isOver = true;
            for (int i = 0; i < pObjectValue.Count; i++)
            {
                //kiem tra vi tri trong con trong' khong
                //tru so luong trong ke
                int? posXId = pObjectValue[i].Invd_POSITION_X_ID;
                if (posXId != null && posXId != 0)
                {
                    position_x_inventory tempX = dao.GetById<position_x_inventory>(posXId);
                    tempX.Posx_Quantity = tempX.Posx_Quantity + pObjectValue[i].Invd_Quantity;
                    dao.Update(tempX);
                    if (tempX.Posx_Quantity < 0)
                    {
                        isOver = false;
                        break;
                    }
                }
                else
                {
                    pObjectValue[i].Invd_POSITION_X_ID = null;
                }

                pObjectValue[i].Invd_Stock_ID = pInward.Inw_Stock_id;
                pObjectValue[i].Invd_UnitPrice = pObjectValue[i].Invd_Price;
                pObjectValue[i].Invd_E_Quantity = pObjectValue[i].Invd_Quantity;
                //pObjectValue[i].Invd_Amount *= vat;
                pObjectValue[i].Invd_E_Amount = pObjectValue[i].Invd_Amount;
                pObjectValue[i].Invd_Description = pInward.Inw_Description;
                pObjectValue[i].Invd_Provider_ID = pInward.Inw_Provider_ID;

                //kiem tra san pham có trong kho chưa
                string temProductDetailId = pObjectValue[i].Invd_PRODUCT_DETAILS_ID;
                string tempStockID = pObjectValue[i].Invd_Stock_ID;
                int? tempPositionX = pObjectValue[i].Invd_POSITION_X_ID;
                var listTempInventory = dao.FindByMultiColumnAnd<inventory>(new[] { "Inv_PRODUCT_DETAILS_ID", "Inv_Stock_ID", "Invd_POSITION_X_ID" },
                    temProductDetailId, tempStockID, tempPositionX);
                inventory tempInventory;
                if (listTempInventory.Count == 0)
                {
                    tempInventory = null;
                }
                else
                {
                    tempInventory = listTempInventory.First();
                }
                //chua có thì add thêm
                if (tempInventory == null)
                {
                    //add inventory
                    inventory inven = new inventory()
                    {
                        Inv_RefID = pInward.Inw_ID,
                        Inv_RefType = (int?)EnumRefType.Inward,
                        Inv_RefDate = pInward.Inw_RefDate,
                        Inv_Stock_ID = pInward.Inw_Stock_id,
                        Inv_Actived = 1,
                        Inv_Description = pInward.Inw_Description,
                        Inv_Ship = newShip
                    };
                    inven.Inv_PRODUCT_DETAILS_ID = pObjectValue[i].Invd_PRODUCT_DETAILS_ID;
                    inven.Inv_Product_Name = pObjectValue[i].Invd_Product_Name;
                    inven.Inv_Quantity = pObjectValue[i].Invd_Quantity;
                    inven.Inv_Amount = pObjectValue[i].Invd_Amount;
                    inven.Invd_POSITION_X_ID = pObjectValue[i].Invd_POSITION_X_ID;
                    inven.Inv_Sale_Price = pObjectValue[i].Invd_Sale_Price;
                    inven.Inv_Retails_Price = pObjectValue[i].Invd_Retails_Price;
                    inven.Inv_Agent_Price = pObjectValue[i].Invd_Agent_Price;
                    pObjectValue[i].Invd_E_Quantity = pObjectValue[i].Invd_Quantity;
                    pObjectValue[i].Invd_E_Amount = pObjectValue[i].Invd_Amount;
                    dao.Add(inven);
                    pObjectValue[i].Invd_INENTORY_ID = inven.Inv_ID;

                } 
                //có rồi thì  += số lượng với +=tổng giá nhập
                else
                {
                    pObjectValue[i].Invd_E_Quantity += tempInventory.Inv_Quantity;
                    pObjectValue[i].Invd_E_Amount += tempInventory.Inv_Amount;
                    tempInventory.Inv_Quantity += pObjectValue[i].Invd_Quantity;
                    tempInventory.Inv_Amount += pObjectValue[i].Invd_Amount;
                    tempInventory.Inv_Sale_Price = pObjectValue[i].Invd_Sale_Price;
                    tempInventory.Inv_Retails_Price = pObjectValue[i].Invd_Retails_Price;
                    tempInventory.Inv_Agent_Price = pObjectValue[i].Invd_Agent_Price;
                    if (tempInventory.Inv_Ship < newShip)
                    {
                        tempInventory.Inv_Ship = newShip;
                    }
                    pObjectValue[i].Invd_INENTORY_ID = tempInventory.Inv_ID;
                    dao.Update(tempInventory);
                }
                //add inventory details
                pObjectValue[i].Invd_RefNo = pInward.Inw_ID;
                pObjectValue[i].Invd_RefDate = pInward.Inw_RefDate;
                pObjectValue[i].Invd_RefType = pInward.Inw_RefType;
                var maxSorted = dao.GetContext<inventory_details>().Set<inventory_details>().Max(p => p.Invd_Sorted);
                pObjectValue[i].Invd_Sorted = maxSorted == null ? 0 : maxSorted + 1;

                pObjectValue[i].Invd_ID = 0;
                dao.Add(pObjectValue[i]);
                //add inward detail
                stock_inward_details inwardDetails = new stock_inward_details()
                {
                    Inws_STOCK_INWARD_ID = pInward.Inw_ID,
                    Inws_RefType = (int)EnumRefType.Inward,
                    Inws_Stock_ID = pInward.Inw_Stock_id,
                    Inws_PRODUCT_DETAILS_ID = pObjectValue[i].Invd_PRODUCT_DETAILS_ID,
                    Inws_Product_Name = pObjectValue[i].Invd_Product_Name,
                    Inws_Quantity = pObjectValue[i].Invd_Quantity,
                    Inws_Amount = pObjectValue[i].Invd_Amount,
                    Inws_UnitPrice = pObjectValue[i].Invd_UnitPrice,
                    Inws_Description = pObjectValue[i].Invd_Description,
                    Inws_POSITION_X_ID = pObjectValue[i].Invd_POSITION_X_ID
                };
                dao.Add(inwardDetails);
            }
            if (isOver)
            {
                return 1;
            }
            else
            {
                ClsMsgBox.Loi("Kệ trong kho không đủ chỗ chứa");
                return 0;
            }
        }

        //public int Add(List<inventory_details> pObjectValue, stock_inward pInward)
        //{

        //    using (sumenEntities objEntities = new sumenEntities())
        //    {
        //        sumenEntitiesSystem objEntitiesSystem = new sumenEntitiesSystem();
        //        DbContextTransaction trans = objEntities.Database.BeginTransaction();
        //        DbContextTransaction transSystem = objEntitiesSystem.Database.BeginTransaction();
        //        try
        //        {
        //            //add inward
        //            decimal vat = (decimal)(1f + (float)pInward.Inw_VAT / 100f);
        //            //pInward.Inw_Amount *= vat;
        //            objEntities.stock_inward.Add(pInward);
        //            objEntities.SaveChanges();

        //            //check ship greater-->update
        //            int sumQuantity = (int)pObjectValue.Sum(s => s.Invd_Quantity);
        //            decimal newShip = (decimal)(pInward.Inw_Ship_Price / sumQuantity);

        //            bool isOver = true;
        //            for (int i = 0; i < pObjectValue.Count; i++)
        //            {
        //                //kiem tra vi tri trong con trong' khong
        //                //tru so luong trong ke
        //                int? posXId = pObjectValue[i].Invd_POSITION_X_ID;
        //                if (posXId != null && posXId != 0)
        //                {
        //                    position_x_inventory tempX =
        //                        objEntities.position_x_inventory.FirstOrDefault(p => p.Posx_ID == posXId);
        //                    tempX.Posx_Quantity = tempX.Posx_Quantity + pObjectValue[i].Invd_Quantity;
        //                    objEntities.SaveChanges();
        //                    if (tempX.Posx_Quantity < 0)
        //                    {
        //                        isOver = false;
        //                        break;
        //                    }
        //                }
        //                else
        //                {
        //                    pObjectValue[i].Invd_POSITION_X_ID = null;
        //                }



        //                pObjectValue[i].Invd_Stock_ID = pInward.Inw_Stock_id;
        //                pObjectValue[i].Invd_UnitPrice = pObjectValue[i].Invd_Price;
        //                pObjectValue[i].Invd_E_Quantity = pObjectValue[i].Invd_Quantity;
        //                //pObjectValue[i].Invd_Amount *= vat;
        //                pObjectValue[i].Invd_E_Amount = pObjectValue[i].Invd_Amount;
        //                pObjectValue[i].Invd_Description = pInward.Inw_Description;
        //                pObjectValue[i].Invd_Provider_ID = pInward.Inw_Provider_ID;

        //                //kiem tra san pham có trong kho chưa
        //                string temProductDetailId = pObjectValue[i].Invd_PRODUCT_DETAILS_ID;
        //                string tempStockID = pObjectValue[i].Invd_Stock_ID;
        //                int? tempPositionX = pObjectValue[i].Invd_POSITION_X_ID;
        //                var tempInventory =
        //                  (from p in objEntities.inventories
        //                   where p.Inv_PRODUCT_DETAILS_ID == temProductDetailId && p.Inv_Stock_ID == tempStockID && p.Invd_POSITION_X_ID == tempPositionX
        //                   select p).FirstOrDefault();
        //                //chua có thì add thêm
        //                if (tempInventory == null)
        //                {
        //                    //add inventory
        //                    inventory inven = new inventory()
        //                    {
        //                        Inv_RefID = pInward.Inw_ID,
        //                        Inv_RefType = (int?)EnumRefType.Inward,
        //                        Inv_RefDate = pInward.Inw_RefDate,
        //                        Inv_Stock_ID = pInward.Inw_Stock_id,
        //                        Inv_Actived = 1,
        //                        Inv_Description = pInward.Inw_Description,
        //                        Inv_Ship = newShip
        //                    };
        //                    inven.Inv_PRODUCT_DETAILS_ID = pObjectValue[i].Invd_PRODUCT_DETAILS_ID;
        //                    inven.Inv_Product_Name = pObjectValue[i].Invd_Product_Name;
        //                    inven.Inv_Quantity = pObjectValue[i].Invd_Quantity;
        //                    inven.Inv_Amount = pObjectValue[i].Invd_Amount;
        //                    inven.Invd_POSITION_X_ID = pObjectValue[i].Invd_POSITION_X_ID;
        //                    inven.Inv_Sale_Price = pObjectValue[i].Invd_Sale_Price;
        //                    inven.Inv_Retails_Price = pObjectValue[i].Invd_Retails_Price;
        //                    inven.Inv_Agent_Price = pObjectValue[i].Invd_Agent_Price;
        //                    pObjectValue[i].Invd_E_Quantity = pObjectValue[i].Invd_Quantity;
        //                    pObjectValue[i].Invd_E_Amount = pObjectValue[i].Invd_Amount;
        //                    objEntities.inventories.Add(inven);
        //                    objEntities.SaveChanges();

        //                    pObjectValue[i].Invd_INENTORY_ID = inven.Inv_ID;

        //                } //có rồi thì  += số lượng với +=tổng giá nhập
        //                else
        //                {
        //                    pObjectValue[i].Invd_E_Quantity += tempInventory.Inv_Quantity;
        //                    pObjectValue[i].Invd_E_Amount += tempInventory.Inv_Amount;
        //                    tempInventory.Inv_Quantity += pObjectValue[i].Invd_Quantity;
        //                    tempInventory.Inv_Amount += pObjectValue[i].Invd_Amount;
        //                    tempInventory.Inv_Sale_Price = pObjectValue[i].Invd_Sale_Price;
        //                    tempInventory.Inv_Retails_Price = pObjectValue[i].Invd_Retails_Price;
        //                    tempInventory.Inv_Agent_Price = pObjectValue[i].Invd_Agent_Price;
        //                    if (tempInventory.Inv_Ship < newShip)
        //                    {
        //                        tempInventory.Inv_Ship = newShip;
        //                    }
        //                    pObjectValue[i].Invd_INENTORY_ID = tempInventory.Inv_ID;
        //                    objEntities.SaveChanges();
        //                }
        //                //add inventory details
        //                pObjectValue[i].Invd_RefNo = pInward.Inw_ID;
        //                pObjectValue[i].Invd_RefDate = pInward.Inw_RefDate;
        //                pObjectValue[i].Invd_RefType = pInward.Inw_RefType;
        //                var maxSorted = objEntities.inventory_details.Max(p => p.Invd_Sorted);
        //                pObjectValue[i].Invd_Sorted = maxSorted == null ? 0 : maxSorted + 1;


        //                pObjectValue[i].Invd_ID = 0;
        //                objEntities.inventory_details.Add(pObjectValue[i]);
        //                objEntities.SaveChanges();
        //                //add inward detail
        //                stock_inward_details inwardDetails = new stock_inward_details()
        //                {
        //                    Inws_STOCK_INWARD_ID = pInward.Inw_ID,
        //                    Inws_RefType = (int)EnumRefType.Inward,
        //                    Inws_Stock_ID = pInward.Inw_Stock_id,
        //                    Inws_PRODUCT_DETAILS_ID = pObjectValue[i].Invd_PRODUCT_DETAILS_ID,
        //                    Inws_Product_Name = pObjectValue[i].Invd_Product_Name,
        //                    Inws_Quantity = pObjectValue[i].Invd_Quantity,
        //                    Inws_Amount = pObjectValue[i].Invd_Amount,
        //                    Inws_UnitPrice = pObjectValue[i].Invd_UnitPrice,
        //                    Inws_Description = pObjectValue[i].Invd_Description,
        //                    Inws_POSITION_X_ID = pObjectValue[i].Invd_POSITION_X_ID
        //                };
        //                objEntities.stock_inward_details.Add(inwardDetails);
        //                objEntities.SaveChanges();


        //            }
        //            if (isOver)
        //            {
        //                trans.Commit();
        //                transSystem.Commit();
        //                return 1;
        //            }
        //            else
        //            {
        //                trans.Rollback();
        //                transSystem.Rollback();
        //                ClsMsgBox.Loi("Kệ trong kho không đủ chỗ chứa");
        //                return 0;
        //            }

        //        }
        //        catch (Exception ex)
        //        {
        //            trans.Rollback();
        //            transSystem.Rollback();
        //            ClsMsgBox.LoiChung(ex, false);
        //            return 0;
        //        }
        //    }
        //}


        public string GetNewId(object pDate, string pStockID)
        {
            using (sumenEntities objEntities = new sumenEntities())
            {
                stock oStock = objEntities.stocks.FirstOrDefault(p => p.stock_id == pStockID);
                if (oStock == null) return "";
                string prefixCode = oStock.stock_CodeInward;
                DateTime pDateTime = (DateTime)pDate;
                string prefix = prefixCode + "-" + pDateTime.ToString("ddMMyy") + "-";
                DateTime date = new DateTime(pDateTime.Year, pDateTime.Month, pDateTime.Day);
                int countMax = (from p in objEntities.stock_inward where p.Inw_RefDate == date select p).Count();
                var query = countMax == null ? 0 : countMax + 1;
                string count = query.ToString().PadLeft(4, '0');
                return prefix + count;
            }

        }



    }
}
